import axios from 'axios'
import store from '@/store/index'
import { Toast } from 'vant'
import router from '@/router'
import JSONBIG from 'json-bigint'

// const baseURL = 'http://localhost:8000'
const baseURL = 'http://toutiao-app.itheima.net'
const request = axios.create({
  baseURL,
  timeout: 5000,
  transformResponse: [function (data) {
    try {
      // 如果转换成功则返回转换的数据结果
      return JSONBIG.parse(data)
    } catch (err) {
      // 如果转换失败，则包装为统一数据格式并返回
      return {
        data
      }
    }
  }]

})
request.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const tokenInfo = store.state.user.token.token
  if (tokenInfo) {
    config.headers.Authorization = 'Bearer ' + tokenInfo
  }
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})
request.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response.data
}, async function (error) {
  // 对响应错误做点什么
  // 判断token失效问题，判断错误信息是否为401
  console.dir(error)
  const tokenInfo = store.state.user.token
  if (error.response.status === 401) {
    // 是401错误，判断是否有刷新token
    console.log(tokenInfo)
    if (!tokenInfo.refresh_token) {
      store.commit('user/removeToken')
      Toast.fail('登录信息过期了')
      router.push({
        path: '/login',
        query: {
          back: router.currentRoute.path
        }
      })
      return
    }
    try {
      const res = await axios({
        method: 'PUT',
        url: baseURL + '/v1_0/authorizations',
        headers: {
          Authorization: 'Bearer ' + tokenInfo.refresh_token
        }
      })
      console.log(res)
      store.commit('user/setToken', {
        token: res.data.data.token,
        refresh_token: tokenInfo.refresh_token
      })
      return request(error.config)
    } catch {
      store.commit('user/removeToken')
      Toast.fail('登录信息过期了')
      router.push({
        path: '/login',
        query: {
          back: router.currentRoute.path
        }
      })
    }
  }
  return Promise.reject(error)
})
export default request
